import JSEncrypt from 'jsencrypt'
import { parseBigInt } from 'jsencrypt/lib/lib/jsbn/jsbn'
const encryptedData = "NmsCanajAMOe8J2OdfrymG4bGOMvPSf90axIb8DZaXeUpddd8Q2/aUq1ez+DXsf7QjtgQ0MNBmLbvCMLh1gxh5Z4zkHB0BAuhzDwnxTS6AFpZKLYWSzYX+mHHQR5KilFQwnSnSgMEkqE6CrYzEJi1QBbmhmihxjUpBjBSZtRS6WYcg0NkFVagR8V+4tNrof9Pcgn1R+Mw3ZzQm4XOukJQbG+b7aVu6TGkE82A87anYjcv3azlQMlb6VWQhbwH2V5Wb/ojJO5P/4lvdRSjiMl0dNe9EPurjhTtsocH9QbDciedBWThLeTeYuqyqxGxxkgqgivCUifRkVuqXO793O1bSnY3Pqs3b5FrBd04TApQBLxeKL+TPIz+Hl8bN00X1Ex1sNIWd97wgSuKa0I6y7SpLh+I0Yy5kEOzArk3fHAb3MLP0sZv5jAxS3Uf56U7eP0kslE/yGvrPliO52/jKXOrR3QJYT9mowAA6aKAvpk0elqo5LMenI+z73Oj8uwEY76hOUaxo+yV7r8N+tod+j+updROxjYZ54qc25KmJyz+f47NOx+xJsbDFEnqcAhZ1pWGmmLQELMAl8PV/slvDzCJOlK0qZxfjO5Sj+IBdkX52RkofOjAk58sW/bTRgLvnvRAX/JUhNjVSRnb5E6ghJwsgejJyuem0uzfKfSeXIguW4=";
const publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAt3H2Q+TKSIlNbjEgl7jHgdPNdV8eFAr6SqRwtcUjlkJlbtl5M5ebPoAiWW0Kar0Sd/6LzpiuTdIx+qCHl9dLuZBL6doR+W6tXj9M6OBA+Rjg7eUwepqIACP6v7nfJW/raWLs2byt486ArXfDKb+HGyaHLMXpKbBlAsenwugD2o8bPYY9B1NBF+aB5WLFOzLYaTkrmJR/D0NjB1Bf6rb0ecgINFCuBcBoOJK9/6XqSlkKOPLqjjl7FW2OWS7SBAj8hvatnWi5Gibm0PEqR6m5UKjVhNUglBKLrEK7KAviIstI0ZqCoJ4wOuZE23U6QFSLOJj2RjPjaFvVRKP7JUVvEwIDAQAB";

// 将公钥转换为CryptoKey对象
export const importPublicKey = async () => {
  const publicKeyData = new TextEncoder().encode(publicKey);
  const importedKey = await crypto.subtle.importKey(
    'spki',
    publicKeyData,
    { name: 'RSA-OAEP', hash: 'SHA-256' },
    true,
    ['decrypt']
  );
  return importedKey;
}

// 解密
export const decryptData = async () => {
  const importedPublicKey = await importPublicKey();

  const encryptedDataArrayBuffer = Uint8Array.from(atob(encryptedData), c => c.charCodeAt(0));
  const decryptedArrayBuffer = await crypto.subtle.decrypt(
    { name: 'RSA-OAEP' },
    importedPublicKey,
    encryptedDataArrayBuffer
  );
  console.log("decryptedArrayBuffer", decryptedArrayBuffer)
  const decryptedData = new TextDecoder().decode(decryptedArrayBuffer);
  console.log("Decrypted data: " + decryptedData);
}



function pkcs1unpad2(d: any, n: any) {
  var b = d.toByteArray()
  var i = 0
  while (i < b.length && b[i] === 0) {
    ++i
  }
  // if (b.length - i !== n - 1 || b[i] !== 2) {
  //   return null
  // }
  ++i
  while (b[i] !== 0) {
    if (++i >= b.length) {
      return null
    }
  }
  var ret = ''
  while (++i < b.length) {
    var c = b[i] & 255
    if (c < 128) { // utf-8 decode
      ret += String.fromCharCode(c)
    } else if ((c > 191) && (c < 224)) {
      ret += String.fromCharCode(((c & 31) << 6) | (b[i + 1] & 63))
      ++i
    } else {
      ret += String.fromCharCode(((c & 15) << 12) | ((b[i + 1] & 63) << 6) | (b[i + 2] & 63))
      i += 2
    }
  }
  return ret
}

function decrypt(data: string, publicKey: string) {
  const encrypt = new JSEncrypt()
  encrypt.setPublicKey(publicKey)
  // 不支持公钥解密
  // 自定义解析方法支持公钥解析
  const rsaKey:any = encrypt.getKey()
  rsaKey.decrypt = function (ctext:any) {
    var c = parseBigInt(ctext, 16)
    var m = this.doPublic(c)
    if (m == null) {
      console.log
      return ''
    }
    const result = pkcs1unpad2(m, ((this.n as any).bitLength() + 7) >> 3)
    console.log("resultbb",result)
    return result?  result: ''
  }
  return encrypt.decrypt(data)
}

// decryptData().catch(console.error);
export default {
  importPublicKey,
  decryptData,
  decrypt
}